#!/usr/bin/env python2

from bs4 import BeautifulSoup as bs
import sqlite3
import os
import time


BASEDIR = os.path.split(os.path.realpath(__file__))[0]

DBFILE = BASEDIR + os.sep + "MonitorMQ.db"


def getHtml(host, port,username,password):
    host = host
    prot = port
    username = username
    password = password
    command = "curl -u"+username+":"+password" http://" + \
        str(host) + ":" + str(port) + "/admin/queues.jsp"
    data = ''
    try:
        data = os.popen(command).read()
        return data
    except Exception as e:
        print str(e)
        return ''


def getTables(html):
    soup = bs(html)
    tables = soup.find_all('table')
    return tables


def getTrs(table):
    table = table
    trs = table.find_all('tr')
    return trs


def getTds(tr):
    tr = tr
    tds = tr.find_all('td')
    return tds


def insertTosqlite(SQL):
    SQL = SQL
    connection = sqlite3.connect(DBFILE)
    cursor = connection.cursor()
    cursor.execute(SQL)
    connection.commit()
    connection.close()


def initDB(DBFILE):
    tablename = "MQmonitor_"+time.strftime('%Y_%m')
    SQL = """create table if not exists %s  (
    id integer PRIMARY KEY autoincrement ,
    name  varchar(90) ,
    Pending int ,
    consumers  int ,
    enqueued  int ,
    dequeued  int ,
    MonitorTime varchar(60)
    )
    """ %tablename
    connection = sqlite3.connect(DBFILE)
    cursor = connection.cursor()
    cursor.execute(SQL)
    connection.commit()
    connection.close()


def main():
    host = '192.168.1.6'
    port = '8161'
    username = admin
    password = admin-admin
    initDB(DBFILE)
    html = getHtml(host, port,username,password)
    tables = getTables(html)
    trs = getTrs(tables[-1])
    lines = []
    SQLs = []
    timestrings = time.strftime("%Y-%m-%d %H:%M:%S")
    tablename = "MQmonitor_"+time.strftime('%Y_%m')
    for tr in trs:
        try:
            tds = getTds(tr)
            # print len(tds)
            # print tds[:5]
            name = tds[0].get_text().strip()
            pending = tds[1].get_text().strip()
            consumers = tds[2].get_text().strip()
            enqueued = tds[3].get_text().strip()
            dequeued = tds[4].get_text().strip()
            lines.append((tablename,name, pending, consumers,
                          enqueued, dequeued, timestrings))
        except Exception as e:
            pass
    for line in lines:
        SQLs.append(
            'insert into %s (name,pending,consumers,enqueued,dequeued,MonitorTime ) values ("%s","%s","%s","%s","%s","%s")' % line)
    for SQL in SQLs:
        #print SQL
        insertTosqlite(SQL)


if __name__ == "__main__":
    main()
